const dbService = require('../service/dbService');
const userService = require('../service/userService');
const { encryption } = require('../utils');
const { STATUS_CODE } = require('../constants');
class UserController {
  async registerUser(ctx) {
    const user = ctx.request.body;
    const result = await dbService.insert(user, 'users');
    const isSuccess = result && result.insertId;
    const resp = {
      code: isSuccess ? STATUS_CODE.SUCCESS : STATUS_CODE.ERROR,
      message: isSuccess ? '注册成功' : '注册失败',
    };
    ctx.makeResp(resp);
  }
  async login(ctx) {
    const { name, password } = ctx.request.body;
    const result = await dbService.query({ name }, 'users');
    const userId = result[0] && result[0].id ? result[0].id : undefined;
    const encryptionPassword = encryption(password);
    const resp = {
      code: userId ? STATUS_CODE.SUCCESS : STATUS_CODE.ERROR,
      message: userId ? '登陆成功' : '登陆失败',
      data: result[0] || undefined,
    };
    // 用户登陆成功
    if (userId) {
      if (result[0].password !== encryptionPassword) {
        ctx.app.emit('error', new Error(STATUS_CODE.PASSWORD_ERROR), ctx);
        return;
      }
      const token = userService.generateToken({
        name,
        password,
        id: userId
      });
      resp.data.token = token;
    }
    ctx.makeResp(resp);
  }
}

module.exports = new UserController();
